extends Node2D
signal ball_emit(dir : Vector2)
signal ball_stop()
signal ball_rotation()

@export var camera : Camera2D
@export var next_scene : PackedScene = preload("uid://kroyadpgf4r4")
@onready var init_pos: Marker2D = $InitPos
@export var camera_zoom : float
@onready var cole_group: Node2D = $ColeGroup
const collion_partic = preload("res://layer/pre/ball_collision_partic.tscn")
var current_cole : Node2D
var is_camera_follow : bool
var ball : CharacterBody2D

func _ready() -> void:
	ball = GlobalData.current_ball
	add_child(ball)
	ball.global_position = init_pos.global_position
	camera.global_position = ball.global_position
	is_camera_follow = true
	ball_emit.connect(_on_ball_emit_event)
	ball_stop.connect(_on_ball_stop_event)
	camera.zoom = Vector2.ONE * camera_zoom
	ball.add_particl_event.connect(_add_particl)
	ball.look_event.connect(_look)

func _on_ball_emit_event(dir : Vector2) -> void :
	if is_same(dir,Vector2.ZERO) : return
	is_camera_follow = true
	var camera_tween = get_tree().create_tween()
	camera_tween.tween_property(camera, "zoom", Vector2(0.5,0.5), 0.4)

func _on_ball_stop_event() -> void :
	is_camera_follow = false
	var camera_tween = get_tree().create_tween()
	camera_tween.tween_property(camera, "zoom", Vector2.ONE * camera_zoom, 0.3)

func _process(delta: float) -> void:
	if is_camera_follow :
		camera.global_position = ball.global_position
	_check_cole()

func _add_particl(pos : Vector2) -> void :
	var particl = collion_partic.instantiate()
	particl.global_position = pos
	call_deferred("add_child",particl)

func _check_cole() -> void :
	if not (current_cole or cole_group.get_children().is_empty()) :
		current_cole = cole_group.get_children().pick_random()
		current_cole.show()

func _look(value : bool) -> void :
	if is_camera_follow : return
	var camera_tween = get_tree().create_tween()
	camera_tween.tween_property(camera, "zoom", Vector2(0.5,0.5) if value else Vector2.ONE * camera_zoom, 0.4)

func _change_scene() -> void :
	remove_child(ball)
	get_tree().call_deferred("change_scene_to_packed",next_scene)
